﻿using Microsoft.EntityFrameworkCore;

using SRM.Application.PageResult.Dtos;
using SRM.Application.PageResult.IServices;
using SRM.Core.Models;
using SRM.Core.Models.Base;
using SRM.Core.Repositories;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SRM.Application.PageResult.ReturnOrderPage
{
    public class ReturnOrderServer : IReturnOrderServer
    {
        private readonly IRepository<ReturnOrder> _returnOrderRepository;

        public ReturnOrderServer(IRepository<ReturnOrder> returnOrderRepository)
        {
            _returnOrderRepository = returnOrderRepository;
        }

        public async Task<PagerModel<ReturnOrder>> GetReturnOrderList(PagerModelInput input)
        {
            var query = _returnOrderRepository
                .GetAll()
                .Include(r => r.PurchaseOrders)
                .AsNoTracking();

            if (!string.IsNullOrEmpty(input.FilterText))
            {
                query = query.Where(s => s.ReturnOrderNo.Contains(input.FilterText));
            }

            if (!LoginUser.LoginUsers.IsHQ)
            {
                query = query.Where(q =>
                q.SupplierId == LoginUser.LoginUsers.SupplierId);
            }

            query = query.Where(q =>
            q.PurchaseOrders.ReviewState == Core.Extension.PurchaseOrderStateEnum.转回货计划);

            var data = await query.ToListAsync();
            data.Sort((ReturnOrder r1, ReturnOrder r2) => r2.CreateDate.CompareTo(r1.CreateDate));

            PagerModel<ReturnOrder> pagerModel = PagedList<ReturnOrder>.PageList(input, data);
            return pagerModel;
        }
    }
}
